var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var POINT_SEPERATION = 1;
var weatherLocations = [];
var WEATHER_URL_BASE = "http://api.wunderground.com/api/cbb7a101847d14b1/conditions/q/location.json";

/**
 * Function to initialize the map
 */
function initialize() {
	directionsDisplay = new google.maps.DirectionsRenderer();

	//TODO: Get this through geolocation 
	var minneapolis = new google.maps.LatLng(44.95, -93.32);

	var myOptions = {
		center : minneapolis,
		zoom : 10,
		mapTypeId : google.maps.MapTypeId.ROADMAP
	};

	map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

	directionsDisplay.setMap(map);

}

/**
 * Function that is called when user submits request
 */
function getDirections() {
	
	//clears existing data from table.
	clearData();
	
	var start = document.getElementById("startPoint").value;
	var end = document.getElementById("endPoint").value;
	
	var request = {
		origin : start,
		destination : end,
		travelMode : google.maps.TravelMode.DRIVING
	};

	directionsService.route(request, directionsServiceCallback);
	
}

/**
 * Callback function for MAPs API
 * @param result
 * @param status
 */
function directionsServiceCallback(result, status) {	
	if (status == google.maps.DirectionsStatus.OK) {
		directionsDisplay.setDirections(result);
		findMarkersAndShowWeather(result);		
	}
}

/**
 * Finds waypoints in the path that are separated by a specific distance
 * @param result - DirectionServiceResponse from GoogleMaps API
 */
function findMarkersAndShowWeather(result) {
	
	if (result.routes.length == 1) {
		var steps = result.routes[0].legs[0].steps;
		var currentPoint;
		var previousPoint = null;
		
		//get weather data for starting point
		getWeatherData(steps[0].start_location);
		
		for ( var i in steps) {
			
			for ( var j = 1; j < steps[i].path.length; j++) {
				currentPoint = steps[i].path[j];
				
				//first time initialization
				//assumes that first few elements in the directions are close to each other.
				if (previousPoint == null) {
					previousPoint = currentPoint;
				}
				
				//find points that are seperated by a given degree
				if ((Math.abs(currentPoint.Za - previousPoint.Za) >= POINT_SEPERATION)
						|| (Math.abs(currentPoint.$a - previousPoint.$a) >= POINT_SEPERATION)) {
										
					//get weather data for that point
					getWeatherData(currentPoint);					
					
					//save current point for calculating next waypoint
					previousPoint = currentPoint;
				}

			}						
		}
		
		//get weather data for starting point
		getWeatherData(steps[steps.length - 1].end_location);
	}
}

/**
 *  Calls weather API for weather data.
 *  @param currentPoint
 */
function getWeatherData(currentPoint) {
	//construct URL that contains location coordinates
	tempUrl = WEATHER_URL_BASE.replace("location", currentPoint.Za + "," + currentPoint.$a);
	
	//make the service call to weather API end-point
	$.ajax({
			url : tempUrl,
			dataType : "jsonp",
			success : function(parsed_json) {	
				//console.log(parsed_json);

				//capture data as json object
				var lat = parseFloat(parsed_json.current_observation.display_location.latitude);
				var lgt = parseFloat(parsed_json.current_observation.display_location.longitude);				
				var weatherData = {					
					location : new google.maps.LatLng(lat,lgt),
					location_city : parsed_json.current_observation.display_location.full,
					temp_f : parsed_json.current_observation.temp_f,
					icon_url : parsed_json.current_observation.icon_url
				};		
				
				//load the information on summary table and map
				loadData(weatherData);			
			}		
	});	
}

/**
 * Create weather summary table with weather data.
 * Adds markers to Map.
 * @param weatherData
 */
function loadData(weatherData){
	if(weatherData){
		//add a row to the table
		var row = "<tr><td>" + weatherData.location_city + "</td><td>" + weatherData.temp_f + "F</td><td><img src=\'" + weatherData.icon_url + "\'>";		
		$("table tr:last").after(row);		
		
		//add a marker to the map
		new google.maps.Marker({
			position : weatherData.location,
			title : weatherData.location_city,
			animation: google.maps.Animation.DROP,
			map : map,
			icon : weatherData.icon_url
		});
	}
}

/**
 * clear summary table data
 */
function clearData(){
	$( "table tr:first").siblings().remove();
}